<template>
  <div class="param-setting">
      <div class="param-setting-main">
          <div class="param-setting-form">
              <div class="setting-form-title">
                  <div class="form-title">表达式</div>
                  <div class="form-title">可选参数</div>
                  <div class="form-title">固定参数</div>
              </div>
              <div class="setting-form-item" v-for="(item, index) in formdataList" :key="index">
                  <div class="form-title express">
                    <div class="express-item">
                     <span> ${ </span>
                       <el-input v-model="item.inputVal" @change="handleChangeExpress(index)" ></el-input>
                      <span> } </span>
                    </div>
                  </div>
                  <div class="form-title">
                     <el-select v-model="item.select" @change="hadleChangeSelect(index)" placeholder="请选择">
                        <el-option
                        v-for="item in options"
                        :key="item.param"
                        :label="item.value"
                        :value="item.param">
                        </el-option>
                    </el-select>
                  </div>
                <div class="form-title">
                  <el-input v-model="item.inputVal2" @input="handleChangeInput(index)"></el-input>
                </div>
                <el-checkbox v-model="item.checked" @change="handleChangeChecked(index)">灵动参数</el-checkbox>
                <div v-if="item.isShow" class="add-btn" @click="addList(index)">
                  <i class="el-icon-plus"></i>
                  继续添加
                </div>
                <div v-if="item.isDelect" class="add-btn remove-btn" @click="removeList(item, index)">
                  <i class="el-icon-close"></i>
                  删除
                </div>
              </div>
          </div>
           <div class="param-setting-form">
              <div class="setting-form-title">
                  <div class="form-title">签名参数</div>
                  <div class="form-title">签名参数</div>
              </div>
              <div class="setting-form-item">
                  <div class="form-item-input">
                    <div class="lable-title">甲方</div>
                    <el-input v-model="partyOneVal" @change="handleChange" class="form-title"></el-input>
                  </div>
                  <div class="form-title">
                     <el-select v-model="partyOne" placeholder="请选择">
                        <el-option
                        v-for="item in options2"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                  </div>
              </div>
              <div class="setting-form-item">
                  <div class="form-item-input">
                    <div class="lable-title">乙方</div>
                    <el-input v-model="partyTwoVal" class="form-title"></el-input>
                  </div>
                  <div class="form-title">
                     <el-select v-model="partyTwo" placeholder="请选择">
                        <el-option
                        v-for="item in options2"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                  </div>
              </div>
          </div>
          <div class="param-setting-btn">
            <el-button type="primary" size="small" @click="sumit">保存</el-button>
            <el-button  plain size="small" @click="backbtn">返回</el-button>
            <el-button plain size="small" @click="handleback">取消</el-button>
          </div>
      </div>
  </div>
</template>

<script>
import { addTemplateList, reviseTemplateList, getParamsList, getoptionlist, newsreviseTemplateList } from '@/api/contractTemplate.js'
//  addTemplateList,
export default {
  data () {
    return {
      postData: '',
      options: [{
        param: '',
        value: ''
      }
      ],
      options2: [
        {
          value: '',
          label: ''
        },
        {
          value: 'signName',
          label: '签名'
        },
        {
          value: 'signStamp',
          label: '签章'
        }
      ],
      partyOne: '', // 甲方选择参数
      partyTwo: '', // 乙方选择参数
      partyOneVal: '', // 甲方填写参数
      partyTwoVal: '', // 乙方填写参数
      isShow: true,
      isadddata: false,
      scopeIdnum: null,
      isindex: 0,
      formdataList: [{
        inputVal: '', // 表达式
        select: '', // 可选参数
        inputVal2: '', // 固定参数
        checked: '', // 是否选中灵动参数
        isShow: true, // 是否展示新增按钮
        isDelect: true // 是否展示删除按钮
      }]
    }
  },
  methods: {
    addList (val) {
      if (this.formdataList[val].inputVal === '') {
        this.$message({
          type: 'warning',
          message: '请填写表达式'
        })
        return false
      } else {
        if (this.formdataList[val].select === '' && this.formdataList[val].inputVal2 === '' && this.formdataList[val].checked === '') {
          this.$message({
            type: 'warning',
            message: '请选择参数或填写参数'
          })
          return false
        }
      }
      this.isindex = val + 1
      // 添加列表
      if (isNaN(Number(val))) {
        this.isShow = false
      } else {
        this.formdataList[val].isShow = false
      }
      const obj = {
        inputVal: '',
        select: '',
        inputVal2: '',
        checked: '',
        isShow: true,
        isDelect: true
      }
      this.formdataList.push(obj)
    },
    sumit () {
      if (this.formdataList[this.isindex].inputVal === '') {
        this.$message({
          type: 'warning',
          message: '请填写表达式'
        })
        return false
      } else {
        if (this.formdataList[this.isindex].select === '' && this.formdataList[this.isindex].inputVal2 === '' && this.formdataList[this.isindex].checked === '') {
          this.$message({
            type: 'warning',
            message: '请选择参数或填写参数'
          })
          return false
        }
      }
      this.adddata()
    },
    adddata () {
      const params = this.formdataList.map(item => {
        if (item.inputVal !== '') {
          let typeId = ''
          let val = ''
          if (item.select !== '') {
            typeId = 1
            val = item.select
          } else if (item.inputVal2 !== '') {
            typeId = 2
            val = item.inputVal2
          } else if (item.checked) {
            typeId = 3
            val = 1
          }
          return {
            expression: item.inputVal,
            paramValue: val,
            typeId: typeId,
            paramTarget: 0,
            scopeId: this.postData.scopeId
          }
        }
      })
      for (var i = 0; i < params.length; i++) {
        if (params[i] === undefined) {
          params.splice(i, 1)
          i = i - 1
        }
      }
      let obj1 = {}
      let obj2 = {}
      if (this.partyOneVal !== '') {
        obj1 = {
          expression: this.partyOneVal,
          paramValue: this.partyOne,
          typeId: this.partyOne === 'signName' ? 4 : 5,
          paramTarget: 1,
          scopeId: this.postData.scopeId
        }
      }
      if (this.partyTwoVal !== '') {
        obj2 = {
          expression: this.partyTwoVal,
          paramValue: this.partyTwo,
          typeId: this.partyTwo === 'signName' ? 4 : 5,
          paramTarget: 2,
          scopeId: this.postData.scopeId
        }
      }
      if (this.partyOneVal !== '') {
        params.push(obj1)
      }
      if (this.partyTwoVal !== '') {
        params.push(obj2)
      }
      this.postData.param = JSON.stringify(params)
      this.postData.userSeq = '1'
      this.postData.cifSeq = '1'
      this.postData.accessHost = '11'
      this.postData.transId = '06234014'
      this.postData.managerName = '李四'
      if (JSON.parse(window.localStorage.getItem('templateDate')) !== null) {
      // 编辑请求
        if (this.postData.isupload === 'up') {
          const data = JSON.parse(window.localStorage.getItem('templateDate'))
          this.postData.managerName = data.managerName
          this.postData.createDate = data.createDate
          this.postData.id = data.id
          this.postData.transId = '06234016'
          this.postData.templateNo = data.templateNo
          const blob = this.basetoblob(this.postData.baseStr)
          const file = this.blobtoflie([blob], this.postData.namefile)
          const formdata = new FormData()
          formdata.append('id', this.postData.id)
          formdata.append('accessHost', this.postData.accessHost)
          formdata.append('cifSeq', this.postData.cifSeq)
          formdata.append('contractLevel', this.postData.contractLevel)
          formdata.append('templateName', this.postData.templateName)
          formdata.append('details', this.postData.details)
          formdata.append('templateNo', this.postData.templateNo)
          formdata.append('file', file)
          formdata.append('enable', this.postData.enable)
          formdata.append('endDate', this.postData.endDate.replace(/-/g, '/'))
          formdata.append('fileName', this.postData.fileName)
          formdata.append('managerName', this.postData.managerName)
          formdata.append('param', this.postData.param)
          formdata.append('scopeId', this.postData.scopeId)
          formdata.append('startDate', this.postData.startDate.replace(/-/g, '/'))
          formdata.append('transId', this.postData.transId)
          formdata.append('typeId', this.postData.typeId)
          newsreviseTemplateList(formdata).then(res => {
            if (res.data.message === 'success') {
              window.localStorage.removeItem('setData')
              this.$message({
                message: '保存成功！',
                type: 'success'
              })
              this.$router.push({
                name:'templateList'
              })
            } else {
              this.$message({
                message: '保存失败！',
                type: 'error'
              })
            }
          })
        } else {
          const data = JSON.parse(window.localStorage.getItem('templateDate'))
          this.postData.managerName = data.managerName
          this.postData.createDate = data.createDate
          this.postData.id = data.id
          this.postData.transId = '06234116'
          this.postData.path = data.path
          this.postData.templateNo = data.templateNo
          const formdata = new FormData()
          formdata.append('id', this.postData.id)
          formdata.append('accessHost', this.postData.accessHost)
          formdata.append('cifSeq', this.postData.cifSeq)
          formdata.append('contractLevel', this.postData.contractLevel)
          formdata.append('templateName', this.postData.templateName)
          formdata.append('templateNo', this.postData.templateNo)
          formdata.append('details', this.postData.details)
          formdata.append('path', this.postData.path)
          formdata.append('enable', this.postData.enable)
          formdata.append('endDate', this.postData.endDate.replace(/-/g, '/'))
          formdata.append('managerName', this.postData.managerName)
          formdata.append('param', this.postData.param)
          formdata.append('scopeId', this.postData.scopeId)
          formdata.append('startDate', this.postData.startDate.replace(/-/g, '/'))
          formdata.append('transId', this.postData.transId)
          formdata.append('typeId', this.postData.typeId)
          reviseTemplateList(formdata).then(res => {
            if (res.data.message === 'success') {
              window.localStorage.removeItem('setData')
              this.$message({
                message: '保存成功！',
                type: 'success'
              })
              this.$router.push({
                name:'templateList'
              })
            } else {
              this.$message({
                message: '保存失败！',
                type: 'error'
              })
            }
          })
        }
      } else {
        // 新增请求
        const blob = this.basetoblob(this.postData.baseStr)
        const file = this.blobtoflie([blob], this.postData.namefile)
        const formdata = new FormData()
        formdata.append('accessHost', this.postData.accessHost)
        formdata.append('cifSeq', this.postData.cifSeq)
        formdata.append('contractLevel', this.postData.contractLevel)
        formdata.append('templateName', this.postData.templateName)
        formdata.append('details', this.postData.details)
        formdata.append('file', file)
        formdata.append('enable', this.postData.enable)
        formdata.append('endDate', this.postData.endDate.replace(/-/g, '/'))
        formdata.append('fileName', this.postData.fileName)
        formdata.append('managerName', this.postData.managerName)
        formdata.append('param', this.postData.param)
        formdata.append('scopeId', this.postData.scopeId)
        formdata.append('startDate', this.postData.startDate.replace(/-/g, '/'))
        formdata.append('transId', this.postData.transId)
        formdata.append('typeId', this.postData.typeId)
        formdata.append('typeId', this.postData.userSeq)
        addTemplateList(formdata).then(res => {
          if (res.data.message === 'success') {
            window.localStorage.removeItem('setData')
            this.$message({
              message: '保存成功！',
              type: 'success'
            })
            this.$router.push('/loanProducts')
          } else {
            this.$message({
              message: '保存失败！',
              type: 'error'
            })
          }
        })
      }
    },
    basetoblob (dataurl) {
      var bstr = atob(dataurl)
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: 'data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,' })
    },
    blobtoflie (theBlob, fileName) {
      return new window.File(theBlob, fileName, { type: this.postData.typefile })
    },
    handleback () {
      // 取消操作
      window.localStorage.removeItem('setData')
      window.localStorage.removeItem('templateDate')
      this.$router.push({
        name:'templateList'
      })
    },
    // 返回
    backbtn () {
      if (this.$route.query.isgin === 'isedit') {
        this.$router.push({
          name:'templateEdit'
        })
      } else {
        this.$router.push({
           name: 'templateAdd',
          query: {
            back: 'back'
          }
        })
      }
    },
    removeList (val, index) {
      // 删除列表
      this.formdataList.splice(index, 1)
      if (this.formdataList.length === 0) {
        this.isShow = true
      } else {
        const num = this.formdataList.length - 1
        this.formdataList[num].isShow = true
      }
    },
    hadleChangeSelect (val) {
      // 选择可选参数校验
      if (this.formdataList[val].inputVal === '') {
        this.$alert('请先填写表达式', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.formdataList[val].select = ''
          }
        })
      }
      if (this.formdataList[val].select !== '') {
        this.formdataList[val].checked = false
        this.formdataList[val].inputVal2 = ''
      }
    },
    handleChangeInput (val) {
      // 填写固定参数校验
      if (this.formdataList[val].inputVal === '') {
        this.$alert('请先填写表达式', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.formdataList[val].inputVal2 = ''
          }
        })
      }
      if (this.formdataList[val].inputVal2 !== '') {
        this.formdataList[val].checked = false
        this.formdataList[val].select = ''
      }
    },
    handleChangeChecked (val) {
      // 选择灵动参数校验
      if (this.formdataList[val].inputVal === '') {
        this.$alert('请先填写表达式', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.formdataList[val].checked = false
          }
        })
      }
      if (this.formdataList[val].checked) {
        this.formdataList[val].inputVal2 = ''
        this.formdataList[val].select = ''
      }
    },
    handleChangeExpress (val) {
      const res = /^[A-Za-z]+$/
      if (!res.test(this.formdataList[val].inputVal)) {
        this.$message({
          message: '请输入英文字母',
          type: 'error'
        })
      }
    },
    handleChange (val) {
      const res = /^[A-Za-z]+$/
      if (!res.test(val)) {
        this.$message({
          message: '请输入英文字母',
          type: 'error'
        })
      }
    },
    // 获取合同模板可选参数列表
    getparamlist () {
      getParamsList({
        transId: '06234018',
        scopeId: this.postData.scopeId,
        accessHost: '20101',
        cifSeq: '300000454'
      }).then(res => {
        if (res.data.code === '000000') {
          res.data.data.list.forEach(element => {
            this.options.push(element)
          })
        }
      })
    }
  },
  mounted () {
    this.postData = JSON.parse(window.localStorage.getItem('setData')) // 获取上一步缓存参数
    // 获取用户已编辑参数并渲染到页面
    if (JSON.parse(window.localStorage.getItem('templateDate')) !== null) {
      const data = JSON.parse(window.localStorage.getItem('templateDate'))
      getoptionlist({
        cifSeq: '1',
        transId: '06234023',
        accessHost: '11',
        templateNo: data.templateNo
      }).then(res => {
        if (res.data.code === '000000') {
          const data = res.data.data.list
          const formData = data.map(item => {
            if (String(item.paramTarget) === '0') {
              var obj = {
                id: 0,
                inputVal: '',
                select: '',
                inputVal2: '',
                checked: '',
                isShow: false,
                isDelect: true
              }
              obj.id = item.id
              obj.inputVal = item.expression
              if (item.typeId === 1) {
                obj.select = item.paramValue
              } else if (item.typeId === 2) {
                obj.inputVal2 = item.paramValue
              } else if (item.typeId === 3) {
                if (item.paramValue === '1') {
                  obj.checked = true
                } else if (item.paramValue === '2') {
                  obj.checked = false
                }
              }
              return obj
            }
          })
          for (var i = 0; i < formData.length; i++) {
            if (formData[i] === undefined) {
              formData.splice(i, 1)
              i = i - 1
            }
          }
          if (formData.length !== 0) {
            this.formdataList = formData
            this.formdataList[0].isDelect = false
            if (this.formdataList[1]) {
              this.formdataList[1].isDelect = false
            }
            this.formdataList[this.formdataList.length - 1].isShow = true
          }
          for (var a = 0; a < data.length; a++) {
            if (String(data[a].paramTarget) === '1') {
              if (data[a].expression !== null) {
                this.partyOneVal = data[a].expression
              }
              if (data[a].paramValue !== null) {
                this.partyOne = data[a].paramValue
              }
            } else if (String(data[a].paramTarget) === '2') {
              if (data[a].expression !== null) {
                this.partyTwoVal = data[a].expression
              }
              if (data[a].paramValue !== null) {
                this.partyTwo = data[a].paramValue
              }
            }
          }
        }
      })
    }
    this.getparamlist()
  }
}
</script>

<style scoped>
.param-setting{
  width: 100%;
  height: 100%;
  background: #fff;
  z-index: 10;
  overflow: auto;
  padding-top: 20px;
}
.param-setting-title {
  height: 64px;
  margin-bottom: 20px;
}
.param-setting-title h3 i{
  width: 4px;
  height: 16px;
  background: #5290FF;
  display: inline-block;
  margin-right: 10px;
  vertical-align: middle;
}
.param-setting-title h3{
  margin: 0 26px;
  padding-left: 3px;
  font-size: 14px;
  line-height: 64px;
  font-weight: bold;
  border-bottom: 1px solid rgba(187, 187, 187, 0.43);
}
.param-setting-main {
   margin: 0 26px;
}
.param-setting-form{
    margin-bottom: 60px;
    padding-left: 20px;
    box-sizing: border-box;
}
.setting-form-title {
    display: flex;
    color: rgba(16, 16, 16);
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 21px;
}
.form-title{
    width: 220px;
}
.setting-form-item{
    display: flex;
    align-items: center;
    margin-bottom: 36px;
}
.setting-form-item >>> .el-input__inner{
    width: 131px;
    height: 30px;
}
.setting-form-item .form-title >>> .el-input__icon{
    line-height: 30px;
}
.add-btn{
  margin-left: 64px;
  color: #207FFD;
  cursor: pointer;
  display: flex;
  align-items: center;
  font-size: 14px;
}
.add-btn i{
  font-size: 24px;
  margin-right: 6px;
}
.form-item-input{
  display: flex;
  align-items: center;
  width: 220px;
}
.lable-title{
  margin-right: 16px;
  font-size: 14px;
}
.form-item-input .form-title{
  width: 131px;
}
.param-setting-btn{
  display: flex;
  justify-content: center;
  padding-top: 100px;
  padding-bottom: 120px;
}
.param-setting-btn >>> .el-button{
    width: 88px;
    height: 32px;
    margin-right: 114px;
}
.remove-btn{
  color: #F56C6C;
}
.express-item{
  display: flex;
  align-items: center;
  width: 130px;
}
.express-item span{
  font-size: 20px;
  margin: 0 5px;
  color: #666;
}
.express-item span:nth-child(1){
  margin-left: 0;
}
</style>
